package cn.leftshine.readme.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.leftshine.readme.MyApplication;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/11/14.
 */

public class FileUtils {

        private static FileUtils fileUtils;
        private final OkHttpClient okHttpClient;

        public static FileUtils get() {
            if (fileUtils == null) {
                fileUtils = new FileUtils();
            }
            return fileUtils;
        }

        public FileUtils() {
            okHttpClient = new OkHttpClient();
        }

        /**
         * @param url 下载连接
         * @param saveDir 储存下载文件的SDCard目录
         * @param fileName
         * @param listener 下载监听
         */
        public void download(final String url, final String saveDir, final String fileName, final OnDownloadListener listener) {
            Request request = new Request.Builder().url(url).build();
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    // 下载失败
                    e.printStackTrace();
                    Log.e("download", "onFailure: ", e);
                    listener.onDownloadFailed();
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    InputStream is = null;
                    byte[] buf = new byte[2048];
                    int len = 0;
                    FileOutputStream fos = null;
                    // 储存下载文件的目录
                    String savePath = isExistDir(saveDir);
                    try {
                        is = response.body().byteStream();
                        long total = response.body().contentLength();
                        //String fileName = getNameFromUrl(url);
                        File file = new File(savePath, fileName);
                        fos = new FileOutputStream(file);
                        long sum = 0;
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                            sum += len;
                            int progress = (int) (sum * 1.0f / total * 100);
                            // 下载中
                            listener.onDownloading(progress);
                        }
                        fos.flush();
                        // 下载完成
                        listener.onDownloadSuccess(file);
                        //MediaStore.Images.Media.insertImage(MyApplication.getContext().getContentResolver(), file.getAbsolutePath(), fileName, null);   //插入图库
                    } catch (Exception e) {
                        //e.printStackTrace();
                        Log.e("download", "onResponse: ",e );
                        listener.onDownloadFailed();
                    } finally {
                        try {
                            if (is != null)
                                is.close();
                        } catch (IOException e) {
                        }
                        try {
                            if (fos != null)
                                fos.close();
                        } catch (IOException e) {
                        }
                    }
                }
            });
        }

        /**
         * @param saveDir
         * @return
         * @throws IOException
         * 判断下载目录是否存在
         */
        private String isExistDir(String saveDir) throws IOException {
            // 下载位置
            File downloadFile = new File(saveDir);
            if (!downloadFile.mkdirs()) {
                downloadFile.createNewFile();
            }
            String savePath = downloadFile.getAbsolutePath();
            return savePath;
        }
        /**
         * @param url
         * @return
         * 从下载连接中解析出文件名
         */
        @NonNull
        public String getNameFromUrl(String url) {
            //return url.substring(url.lastIndexOf("/") + 1);
            String substring = url.substring(url.lastIndexOf("/") + 1);
            String suffixes="avi|mpeg|3gp|mp3|mp4|wav|bmp|jpeg|gif|jpg|png|apk|exe|txt|html|htm|java|doc";
            String file=url.substring(url.lastIndexOf('/')+1);//截取url最后的数据
            Pattern pat=Pattern.compile("[\\S]+[\\.]("+suffixes+")");//正则判断
            Matcher mc=pat.matcher(file);
            while(mc.find()){
                substring = mc.group();//截取文件名后缀名

                //Log.e("substring:", substring);
            }

            return  substring;

        }

        public interface OnDownloadListener {
            /**
             * 下载成功
             */
            void onDownloadSuccess(File file);

            /**
             * @param progress
             * 下载进度
             */
            void onDownloading(int progress);

            /**
             * 下载失败
             */
            void onDownloadFailed();
        }
}
